package com.xnfh.home.viewmodel

import com.xnfh.common.bean.BaiDuCoddingBean
import com.xnfh.common.bean.CropBean
import com.xnfh.common.manager.UserInfoManager
import com.xnfh.framework.base.BaseViewModel
import com.xnfh.framework.bean.RespStateData
import com.xnfh.framework.ext.getDateYMD
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import org.json.JSONObject
import java.io.File

/**
 * @Description:
 * @Author: ziheng
 * @CreateDate: 2023/11/20 14:06
 * @UpdateUser: ziheng
 * @UpdateDate: 2023/11/20 14:06
 * @UpdateRemark: 更新说明
 */
class EnclosureFieldViewModel : BaseViewModel() {


    val geoCodding = RespStateData<BaiDuCoddingBean>()
    val cropList = RespStateData<List<CropBean>>()
    val addField = RespStateData<Any>()

    private val enclosureFieldRes = EnclosureFieldRes()

    /**
     * 百度逆地理编码
     */
    fun requestGeoCodding(location: String) = launch {
        enclosureFieldRes.requestGeoCodding(location, geoCodding)
    }

    /**
     * 获取作物列表
     */
    fun requestCropList() = launch {
        val jsonObject = JSONObject()
        jsonObject.put("scLevel", "2")
        enclosureFieldRes.requestCropList(creatRequestBody(jsonObject.toString()), cropList)
    }

    /**
     * 添加地块
     */
    fun requestAddField(
        imageFile: File,
        fieldName: String,
        address: String,
        fieldArea: Float,
        cropId: String,
        time: Long,
        coordinate: String,
        districtId: String?
    ) = launch {
        //1.创建MultipartBody.Builder对象
        val builder = MultipartBody.Builder()
            .setType(MultipartBody.FORM)
        val body: RequestBody =
            RequestBody.create(MediaType.parse("multipart/form-data"), imageFile) //表单类型
        builder.addFormDataPart("file", imageFile.name, body) //田块截图，图片文件流
        builder.addFormDataPart("userPid", UserInfoManager.instance.getUserInfo()?.suId) //
        builder.addFormDataPart("fieldName", fieldName) //田块名称
        builder.addFormDataPart("address", address) //田块地址
        builder.addFormDataPart("areaMu", fieldArea.toString()) //田块亩数
        builder.addFormDataPart("plantCropId", cropId) //作物id
        builder.addFormDataPart("startTime", time.getDateYMD()) //开始时间
        builder.addFormDataPart("borderCoordinate", coordinate) //田块边界坐标
        builder.addFormDataPart("countyId", districtId) //县编码
        builder.addFormDataPart(
            "fieldFarm",
            UserInfoManager.instance.getUserInfo()?.suOrganizeid
        ) //农场id
        val parts = builder.build().parts()
        enclosureFieldRes.requestAddField(parts, addField)
    }


}